<template>
    <a-modal :keyboard="false" :maskClosable="false" title="消息管理" :open="visible" :width="1000"
        :confirmLoading="loading" centered @cancel="handleCancel">
        <div class="chat-right-right-wrap-item" ref="scrollRef">
            <div class="flex justify-center loading-wrap" v-if="state.loading">
                <loading-outlined />
                数据加载中...
            </div>
            <div class="flex justify-center items-center h-100" v-if="messageList.length == 0 && state.end">
                <a-empty></a-empty>
            </div>
            <div class="chat-item-list" v-for="(item, index) in messageList" :key="index" :class="`chatItem${index}`">
                <div class="chat-item-list-date">{{ item.msgtimeFormat }}</div>
                <div class="chat-item-list-left flex">
                    <a-avatar shape="square" :size="40" :src="item.senderAvatar" v-if="item.senderAvatar"></a-avatar>
                    <a-avatar :size="40" v-else shape="square">
                        <template #icon><user-outlined /></template>
                    </a-avatar>
                    <div class="flex-1">
                        <div class="chat-item-list-nick">{{ item.senderName }}</div>
                        <chat-content :item="item" :isLeft="true"></chat-content>
                    </div>
                </div>
                <!-- <div class="chat-item-list-right flex w-full justify-end" v-else>
                    <div class="flex-1">
                        <div class="chat-item-list-nick">{{ item.senderName }}</div>
                        <chat-content :item="item"></chat-content>
                    </div>
                    <a-avatar shape="square" :size="40" :src="item.senderAvatar" v-if="item.senderAvatar"></a-avatar>
                    <a-avatar :size="40" v-else shape="square">
                        <template #icon><UserOutlined /></template>
                    </a-avatar>
                </div> -->
            </div>
        </div>
        <template #footer>
            <a-space>
                <a-button type="primary" ghost @click="handleAction('down')">下翻</a-button>
                <a-button type="primary" ghost @click="handleAction('up')">上翻</a-button>
            </a-space>
        </template>
    </a-modal>
</template>

<script lang="ts" setup>
    import { reactive, ref, watchEffect, watch, nextTick } from 'vue';
    import { UserOutlined, LoadingOutlined } from '@ant-design/icons-vue';
    import { cloneDeep, isUndefined } from 'lodash-es';
    import { messageQuery } from '@/api/smss/chat';
    import chatContent from './chat-content.vue';
    import { useInfiniteScroll } from '@vueuse/core';
    import { isNotEmpty } from '@/utils/is';
    import { toStringJSON } from 'xe-utils';

    const visible = ref<boolean>(false);

    const emit = defineEmits(['cancel', 'success']);

    const loading = ref(false);
    const defaultForm = {};
    const modelRef = reactive<any>(cloneDeep(defaultForm));
    const scrollRef = ref<any>(null);
    const messageList = ref([]);
    const state = reactive<any>({
        current: 1,
        clientId: '',
        loading: false,
        end: false,
        scrollTop: 0,
        direction: 'up',
    });

    const { isLoading } = useInfiniteScroll(
        scrollRef,
        (data: any) => {
            // load more
            loadMore();
        },
        {
            distance: 20,
            direction: 'top',
            canLoadMore: () => !state.end && isNotEmpty(modelRef.msgId),
        },
    );

    // 异步数据加载
    const fetchData = async current => {
        return new Promise(resolve => {
            const { msgid, roomid, tolist, msgfrom } = modelRef;
            const params: any = {
                current,
                size: 50,
                msgid,
                isSingleChat: !isNotEmpty(roomid),
                direction: state.direction,
            };
            if (!isNotEmpty(roomid)) {
                params.recipient = tolist;
                params.sender = msgfrom;
            } else {
                params.roomid = roomid;
            }
            messageQuery(params).then(res => {
                const { records = [], pages, current } = res.data;
                if (pages > current) {
                    state.current++;
                }
                state.end = pages <= current;

                resolve(
                    state.direction === 'down' ? records
                        .map(item => ({
                            ...item,
                            msgdata: toStringJSON(item.msgdata),
                        }))
                         : records
                        .map(item => ({
                            ...item,
                            msgdata: toStringJSON(item.msgdata),
                        }))
                        .reverse(),
                    
                );
            });
        });
    };

    const loadMore = async () => {
        if (state.loading) return;
        state.loading = true;
        let scrollTop = 0;
        if (scrollRef.value) {
            scrollTop = scrollRef.value.scrollHeight;
        }

        try {
            if (!isNotEmpty(modelRef.msgid)) return false;
            if (state.end) return false;
            const newItems: any = await fetchData(state.current);
            console.log(newItems);
            messageList.value.unshift(...newItems);

            nextTick(() => {
                if (scrollRef.value) {
                    scrollRef.value.scrollTop = scrollRef.value.scrollHeight - scrollTop;
                }
            });
        } catch (error) {
            console.error('加载失败', error);
        } finally {
            state.loading = false;
        }
    };

    const handleReset = () => {
        state.current = 1;
        state.end = false;
        messageList.value = [];
        state.loading = false;

        loadMore();
    };

    const handleAction = type => {
        state.direction = type;

        handleReset();
    };

    const handleCancel = () => {
        visible.value = false;
        Object.keys(modelRef).forEach(key => {
            delete modelRef[key];
        });
        Object.assign(modelRef, cloneDeep(defaultForm));
    };

    const init = async data => {
        console.log(data);
        Object.assign(modelRef, data);

        visible.value = true;
        handleReset();
    };

    defineExpose({
        init,
    });
</script>

<style lang="less" scoped>
.chat-right-right-wrap-item {
    height: 500px;
    overflow-y: auto;
    padding: 15px;

    .chat-item-list {
        margin-top: 10px;
        border-top: 1px solid #f7f7f7;

        &>div {
            &.chat-item-list-date {
                text-align: center;
                color: #aaa;
                font-size: 14px;
                width: 100%;
                margin: 10px 0 5px;
            }

            .chat-item-list-nick {
                margin-bottom: 10px;
            }
        }

        .chat-item-list-left,
        .chat-item-list-right {
            .content-wrap {
                width: 100%;

                .content {
                    display: inline-block;
                    padding: 5px 10px;
                    line-height: 24px;
                    font-size: 15px;
                    border-radius: 8px;
                    word-break: break-all;
                    cursor: pointer;
                    max-width: 60%;
                }
            }
        }

        .chat-item-list-left {
            .content {
                background-color: #fff;
            }

            &>.ant-avatar {
                margin-right: 15px;
                flex-shrink: 0;
            }
        }

        .chat-item-list-right {
            .content {
                background-color: #95ec69;
            }

            &>.ant-avatar {
                margin-left: 15px;
                flex-shrink: 0;
            }

            .chat-item-list-nick {
                text-align: right;
            }
        }
    }
}
</style>
